#pragma once
#include <sys/epoll.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include "Log.hpp"
#include "NoCopy.hpp"
class Epoller : public NoCopy
{
public:
    Epoller(int timeout):_timeout(timeout)
    {
        if((_epfd = epoll_create(1)) < 0)
        {
            lg(Error, "epoll_create err, errstring: %s", strerror(errno));
        }
        else
        {
            lg(Info, "epoll_create success, epoll fd: %d", _epfd);

        }
    }
    int EpollWait(struct epoll_event events[], int num)
    {
        int n = epoll_wait(_epfd, events, num, _timeout);
        if(n > 0)
        {
            return n;
        }
        else if(n == 0)
        {
            lg(Info, "timeout...");
            return 0;
        }
        else
        {
            lg(Error, "epoll_wait err, errstring: %s", strerror(errno));
            return -1;
        }
    }

    void EpollCTL(int op, int fd, uint32_t events)
    {
        int n = 0;
        if(op == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, op, fd, nullptr);
        }
        else
        {
            struct epoll_event event;
            event.events = events;
            event.data.fd = fd;
            n = epoll_ctl(_epfd, op, fd, &event);
        }
        if(n < 0)
        {
            lg(Error, "epoll_ctl err, errstring: %s", strerror(errno));
        }
    }

    ~Epoller()
    {
        close(_epfd);
    }
private:
    int _epfd;
    int _timeout;
};